/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.acme.controller;

import com.acme.business.StockBusiness;
import com.acme.business.StockPriceBusiness;
import com.acme.model.Stock;
import com.acme.model.StockPrice;
import com.acme.persistence.StockDao;
import com.acme.rest.QuoteVO;
import com.acme.rest.StockVO;
import com.acme.rest.YQLclient;
import java.util.Iterator;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Transactional
@Controller  
public class StockController {
	
    @Autowired
    private StockDao stockDao;
    @Autowired
    private StockPriceBusiness stockPriceBusiness;
    @Autowired
    private StockBusiness stockBusiness;
    /**
     *  Este methodo se llama con:
     *  http://localhost:8084/StocksAnalisis/StockController/ 
     *  Notar la "/" al final que es muy importante
     */
    
    
    @RequestMapping(value = "/Stock/listAll", method = RequestMethod.GET)
    public String listStocks(ModelMap model)  throws Exception {
        System.out.println("CLASS: StockController. METHOD: listStocks. ENTER");
        
        //List<Stock>lstStock = ;
        
        model.addAttribute("command", new Stock());
        model.addAttribute("lstStock", stockBusiness.getAllStocks());
        //model.addAttribute("stockDao", stockDao.findAll());
       // model.addAttribute("lstStock", stockPriceBusiness.getAllStockPrice());      
        //YQLclient client = new YQLclient();
        //StockVO result = (StockVO)client.doCall("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.historicaldata%20where%20symbol%20in%20(%22MSFT%22)%20and%20startDate%3D%222011-2-12%22%20and%20endDate%3D%222011-2-15%22%0A%09%09&diagnostics=true&env=http%3A%2F%2Fdatatables.org%2Falltables.env", StockVO.class);
        //System.out.println("getHigh: " + result.getQuotes().get(0).getHigh());

        return "listStocks";
    }

    @RequestMapping(value = "/Stock/add", method = RequestMethod.POST)
    public String addStock(@ModelAttribute("stock") Stock stock, BindingResult result)  throws Exception {
        System.out.println("CLASS: StockController. METHOD: addStock. ENTER");
    	stockDao.create(stock);

        return "successMsg";
    }

    @RequestMapping("/Stock/delete/{stockId}")
    public String deleteStock(@PathVariable("stockId") Long stockId)  throws Exception {
        System.out.println("CLASS: StockController. METHOD: delete. ENTER");
        
        System.out.println("stockId: " + stockId);
    	stockDao.delete(stockDao.findById(stockId));

        return "successMsg";
    }

    @RequestMapping(value = "/Stock/showStock/{symbol}", method = RequestMethod.GET)
    public String showStock(@PathVariable("symbol") String symbol, ModelMap model) throws Exception {      
        
        //ApplicationContext context = new ClassPathXmlApplicationContext("/mvc-dispatcher-servlet.xml");
        //StockBusiness stockBusiness = (StockBusiness) context.getBean("stockBusiness"); 
        //StockPriceBusiness stockPricesBusiness = (StockPriceBusiness) context.getBean("StockPricesBusiness"); 
        
        //stockBusiness.createStock("TS.BA", "Tenaris", "Metalurgica");
        //stockBusiness.findBySymbol(null);
        //List<Stock> argentinianStocks = stockBusiness.getAllStocks();
        
        YQLclient client = new YQLclient();
        StockVO result;
        
        Stock stock = new Stock();
        stock.setName("dfdfd");
        model.addAttribute("command", stock);
        
        //for (Iterator<Stock> it = argentinianStocks.iterator(); it.hasNext();) {
            //stock = it.next();
            //stock = stockBusiness.getStock(1);

            List<Stock> lstStock = stockBusiness.findBySymbol(symbol);
            if (!lstStock.isEmpty()){
                stock = lstStock.get(0);
                result = (StockVO)client.doCall("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.historicaldata%20where%20symbol%20in%20(%22" + stock.getSymbol() + "%22)%20and%20startDate%3D%222011-2-12%22%20and%20endDate%3D%222011-2-15%22%0A%09%09&diagnostics=true&env=http%3A%2F%2Fdatatables.org%2Falltables.env", StockVO.class);
            
                QuoteVO quote;
                StockPrice stockPrice;
                for (Iterator<QuoteVO> it1 = result.getQuotes().iterator(); it1.hasNext();) {
                    quote = it1.next();
                    stockPrice = new StockPrice();
                    stockPrice.setStock_id(stock.getStock_id());
                    stockPrice.setAdjustedClosePrice(Double.toString(quote.getAdjClose()));
                    stockPrice.setClosePrice(Double.toString(quote.getClose()));
                    stockPrice.setHighPrice(Double.toString(quote.getHigh()));
                    stockPrice.setLowPrice(Double.toString(quote.getLow()));
                    stockPrice.setMarket_id(02);
                    stockPrice.setOpenPrice(Double.toString(quote.getOpen()));
                    stockPrice.setPriceDate(quote.getDate().toString());
                    stockPrice.setVolume(Long.toString(quote.getVolume()));

                    stockPriceBusiness.createStockPrice(stockPrice);

                    model.addAttribute("stock", stock);
                    model.addAttribute("command", stock);
                    model.addAttribute("stockPriceDao", stockPriceBusiness.getAllStockPrice());
                }                   
            }
            
        //return "showStock";
        return "stockForm";
    }
    
}
